package com.czx.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czx.entity.User;
import com.czx.common.exception.ExceptionsEnum;
import com.czx.common.exception.FileFailException;
import com.czx.mapper.UserMapper;
import com.czx.service.fileUploadService;
import com.czx.common.utils.R;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
@Service
public class fileUploadServiceImpl extends ServiceImpl<UserMapper, User> implements fileUploadService {
     @Autowired
    private UploadManager uploadManager;
    @Value("${blog.qiniuyun.ak}")
    private String ak;
    @Value("${blog.qiniuyun.sk}")
    private String sk;
    @Value("${blog.qiniuyun.bucket}")
    private String bucket;
    @Value("${blog.qiniuyun.host}")
    private String host;
    @Override
    public R upload(MultipartFile file, User user) {
        if(user==null){
            return R.fail("登录失败");
        }
        //获取文件名称
        String fileName = file.getOriginalFilename();
        //认证
        Auth auth = Auth.create(ak, sk);
        //返回token
        String upToken = auth.uploadToken(bucket,fileName);
        String path=null;
        try {
            Response response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null);
            //本来是Gson，现在用fastjson来代替，
            DefaultPutRet defaultPutRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
            //defaultPutRet.key表示上传成功后返回的文件名
            path=host+defaultPutRet.key;
        } catch (IOException e) {
            throw new FileFailException(ExceptionsEnum.FILE_FAIL.getCode(),ExceptionsEnum.FILE_FAIL.getMsg());
        }
        //把数据添加到数据库
        user.setHeaderUrl(path);
        int i = baseMapper.updateById(user);
        if (i>0) {
            return R.success("图片修改成功");
        }
        throw new FileFailException(ExceptionsEnum.FILE_FAIL.getCode(),ExceptionsEnum.FILE_FAIL.getMsg());

    }
}
